//
//  HTTPHelper.m
//  News
//
//  Created by xalo on 16/2/25.
//  Copyright © 2016年 News. All rights reserved.
//

#import "HTTPHelper.h"
#import "FMDatabase+Database.h"
#import <AFNetworking.h>
#import "VideoModel.h"
#import "NewsModel.h"
#import "PicListModel.h"
#import "DetialModel.h"
#import "CommentModel.h"
@interface HTTPHelper ()

@end

@implementation HTTPHelper


+(_Nonnull id)sharedManger
{
    static HTTPHelper *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        handle = [[HTTPHelper alloc]init];
        
    });
    
    return handle;
}


//请求网络数据
-(void)fetchDataWithUrl:(NSString *)url block:(Block)block {

    [[AFHTTPSessionManager manager] GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        //nothing;
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        block(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"数据请求失败");
        
    }];

}


//请求数据,请求失败执行block
-(void)fetchDataWithUrl:(NSString *)url block:(Block)block reblock:(Block3)reblock {
    
    [[AFHTTPSessionManager manager] GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        //nothing;
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        block(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"数据请求失败");
        reblock();
        
    }];
    
}








#pragma mark - 新闻
// 懒加载 newsModelArray
- (NSMutableArray *)newsModelArray {
    if (!_newsModelArray) {
        _newsModelArray = [NSMutableArray array];
    }
    return _newsModelArray;
}

// 加载新闻model数据
- (void)downloadNewsModelWithChannel:(NSString *)channel subCategoryArray:(NSMutableArray*)subCategoryArray block:(Block1)block reblock:(Block3)block3 {
    
    [self fetchDataWithUrl:[NSString stringWithFormat:@"http://api.sina.cn/sinago/list.json?channel=%@",channel] block:^(id  _Nullable responseObject) {
        
        NSArray *array = responseObject[@"data"][@"list"];
        for (NSDictionary *dict in array) {
            
            NewsModel *model = [[NewsModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            if (([model.category isEqualToString:@"cms"] || [model.category isEqualToString:@"hdpic"])&&(![subCategoryArray containsObject:model])) {
                
                [subCategoryArray addObject:model];
            }
            
        }
                
        [[FMDatabase shareManager] saveModel:array withChannel:channel];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            block();
        });

    } reblock:^{
        
        block3();
    }];
    
    
    
}


#pragma mark - 视频

-(void)fetchVideo_videoDataWithchannel:(NSString * _Nullable)channel videoArray:(NSMutableArray * _Nullable)videoArray block:(Block1 _Nullable)block
{

    
    NSString *url = [NSString stringWithFormat:Kvideo_videoUrl,channel];
    
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
    
            [[HTTPHelper sharedManger] fetchDataWithUrl:url block:^(id  _Nullable responseObject) {
    
                NSDictionary *dict = responseObject[@"data"];
                NSArray *array = dict[@"list"];
    
                for (NSDictionary *dict in array) {
    
    
                    VideoModel *model = [[VideoModel alloc]init];
    
                    NSArray *array = [dict allKeys];
                    for (NSString *string in array) {
                        if ([string isEqualToString:@"video_info"]) {
    
                            NSDictionary *dict1 = dict[@"video_info"];
                            [model setValuesForKeysWithDictionary:dict1];
                        }
                    }
    
                    [model setValuesForKeysWithDictionary:dict];
                    [videoArray addObject:model];
    
                }
    
                [[FMDatabase shareManager] saveModel:array withChannel:channel];
    
    
                dispatch_async(dispatch_get_main_queue(), ^{
    
                    block();
            });
    
        }];

    });
    
}



-(void)fetchVideo_videoDataWithchannel:(NSString *)channel videoArray:(NSMutableArray *)videoArray block:(Block1)block reblock:(Block3)reblock successBlock:(Block)successBlock {
    
        NSString *url = [NSString stringWithFormat:Kvideo_videoUrl,channel];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [[HTTPHelper sharedManger] fetchDataWithUrl:url block:^(id  _Nullable responseObject) {
            
            successBlock(responseObject);
            
            
            NSDictionary *dict = responseObject[@"data"];
                        NSArray *array = dict[@"list"];
            
                        for (NSDictionary *dict in array) {
            
            
                            VideoModel *model = [[VideoModel alloc]init];
            
                            NSArray *array = [dict allKeys];
                            for (NSString *string in array) {
                                if ([string isEqualToString:@"video_info"]) {
            
                                    NSDictionary *dict1 = dict[@"video_info"];
                                    [model setValuesForKeysWithDictionary:dict1];
                                }
                            }
                            
                            [model setValuesForKeysWithDictionary:dict];
                            [videoArray addObject:model];

                        }
            [[FMDatabase shareManager] saveModel:array withChannel:channel];
            
            
                        dispatch_async(dispatch_get_main_queue(), ^{
            
                            block();
                        });

            
        } reblock:^{
            
            
            reblock();
            
        }];
        
        
    });
    
 
}


#pragma mark 上啦加载
-(void)pullUpRefreshDataWithChannel:(NSString *)channel times:(NSInteger)times videoArray:(NSMutableArray *)videoArray block:(Block1)block

{

    NSString *url = [NSString stringWithFormat:KpullUp,times,channel];
    

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [[HTTPHelper sharedManger] fetchDataWithUrl:url block:^(id  _Nullable responseObject) {
            
            NSDictionary *dict = responseObject[@"data"];
            NSArray *array = dict[@"list"];
            
            for (NSDictionary *dict in array) {
                
                
                VideoModel *model = [[VideoModel alloc]init];
                
                NSArray *array = [dict allKeys];
                for (NSString *string in array) {
                    if ([string isEqualToString:@"video_info"]) {
                        
                        NSDictionary *dict1 = dict[@"video_info"];
                        [model setValuesForKeysWithDictionary:dict1];
                    }
                }
                
                [model setValuesForKeysWithDictionary:dict];
                [videoArray addObject:model];
                
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                block();
            });
            
        }];
        
        
    });

}





//上啦加载,如果加载失败执行block

-(void)pullUpRefreshDataWithChannel:(NSString *)channel times:(NSInteger)times videoArray:(NSMutableArray *)videoArray block:(Block1)block reblock:(Block3)reblock
{
    NSString *url = [NSString stringWithFormat:KpullUp,times,channel];
    
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [[HTTPHelper sharedManger] fetchDataWithUrl:url block:^(id  _Nullable responseObject) {
            
            
            NSDictionary *dict = responseObject[@"data"];
            NSArray *array = dict[@"list"];
            
            for (NSDictionary *dict in array) {
                
                
                VideoModel *model = [[VideoModel alloc]init];
                
                NSArray *array = [dict allKeys];
                for (NSString *string in array) {
                    if ([string isEqualToString:@"video_info"]) {
                        
                        NSDictionary *dict1 = dict[@"video_info"];
                        [model setValuesForKeysWithDictionary:dict1];
                    }
                }
                
                [model setValuesForKeysWithDictionary:dict];
                [videoArray addObject:model];
                
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                block();
            });
            
            
            
        } reblock:^{
            
            reblock();
            
            
        }];
        
        
    });
    
    
}





#pragma mark - 图片

//获取当前的数据
-(void)fetchPictureDataWithUrl:(NSString *)url  picArray:(NSMutableArray*)picArray  block:(Block3)block {
    
    NSString *uRL = kP(url);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    
    [[HTTPHelper sharedManger] fetchDataWithUrl:uRL block:^(id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject[@"data"];
        
        NSArray *dataArray = dic[@"list"];
        
        for (NSDictionary *dicList in dataArray) {
            
            PicListModel *picMod = [[PicListModel alloc]init ];
            
            NSDictionary *totalDic = dicList[@"comment_count_info"];
            NSInteger num = [totalDic[@"total"] integerValue];
            
            picMod.Total = num;
            
            
            [picMod setValuesForKeysWithDictionary:dicList];
            
            [picArray addObject:picMod];
            
            NSLog(@"%@",NSHomeDirectory());
            
            [[FMDatabase shareManager] saveModel:dataArray withChannel:url];
            
            
                dispatch_async(dispatch_get_main_queue(), ^{
                
                block();
            });
            
        }
        
    }];
});
    
}


//上拉刷新
-(void)getDropDownLoadDataWith:(NSString *)url number:(NSInteger)number picArray:(NSMutableArray *)picArray  block:(Block3)block  reblock:(Block1)reblock {
    
    NSString *URL = kDown(number, url);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
    [[HTTPHelper sharedManger] fetchDataWithUrl:URL block:^(id  _Nullable responseObject) {
        
        reblock();
        
        NSDictionary *dic = responseObject[@"data"];
        
        NSArray *dataArray = dic[@"list"];
        
        for (NSDictionary *dicList in dataArray) {
            
            PicListModel *picMod = [[PicListModel alloc]init ];
            
            NSDictionary *totalDic = dicList[@"comment_count_info"];
            NSInteger num = [totalDic[@"total"] integerValue];
            
            picMod.Total = num;
            
            
            [picMod setValuesForKeysWithDictionary:dicList];
            
            [picArray addObject:picMod];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                block();
            });
                    
        }
        
        
        
    }];
    
});

}


//详情的方法
-(void)entDetailsInterfaceWithNumber:(NSString *)number picArray:(NSMutableArray *)picArray  block:(Block3)block{
    
    NSString *uRL = kASD(number) ;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    
    [[HTTPHelper sharedManger] fetchDataWithUrl:uRL block:^(id  _Nullable responseObject) {
        
        NSDictionary *dataDic = responseObject[@"data"];
        
        NSArray *array = dataDic[@"pics_module"];
        
        for (NSDictionary *dic in array) {
            
            NSMutableArray *dataArray = dic[@"data"];
    
            for (NSDictionary *dict in dataArray) {
                
                DetialModel *detialModel = [[DetialModel alloc]init];
                
                [detialModel setValuesForKeysWithDictionary:dict];
                
                [picArray addObject:detialModel];
            }
            
            [[FMDatabase shareManager] saveModel:dataArray withChannel:number];
        }
        
          dispatch_async(dispatch_get_main_queue(), ^{
            
            block();
        });
     }];
  });
}

//下拉加载
-(void)getDropUpLoadDataWith:(NSString *)url number:(NSInteger)number picArray:(NSMutableArray *)picArray  block:(Block3)block {
    
    NSString *URL = kUp(number, url);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
    [[HTTPHelper sharedManger] fetchDataWithUrl:URL block:^(id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject[@"data"];
        
        NSArray *dataArray = dic[@"list"];
        
        for (NSDictionary *dicList in dataArray) {
            
            PicListModel *picMod = [[PicListModel alloc]init ];
            
            NSDictionary *totalDic = dicList[@"comment_count_info"];
            NSInteger num = [totalDic[@"total"] integerValue];
            
            picMod.Total = num;
            
            
            [picMod setValuesForKeysWithDictionary:dicList];
            
            [picArray addObject:picMod];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                block();
            });
            
        }
        
    }];
    
    });
}


//评论
-(void)getPictureCommentWith:(NSMutableArray *)Commentarray  number:(NSString *)number  time:(NSInteger)time  block:(Block1)block {
    
    NSString *URL = kConmment(time,number);
       
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [[HTTPHelper sharedManger]fetchDataWithUrl:URL block:^(id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject[@"data"];
        
        NSArray *array = dic[@"cmntlist"];
            
        for (NSDictionary *dic in array) {
            
        CommentModel *comment = [[CommentModel alloc]init];
            
            [comment setValuesForKeysWithDictionary:dic];
            
            [Commentarray addObject:comment];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            block();
            
         });
        
       }];
    
    });
    
}

@end
